<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import Upload from '@/components/Upload/index.vue';
import { uploadFile } from '@/api/upload';

// 上传组件引用
const uploadRef = ref();

// 文件列表
const fileList = ref<any[]>([]);

// 上传配置
const uploadConfig = {
  action: '/api/upload', // 上传接口地址
  headers: {
    'Authorization': 'Bearer ' + localStorage.getItem('token')
  },
  data: {
    // 额外的上传参数
    folder: 'images'
  },
  multiple: true, // 支持多文件上传
  accept: 'image/*,.pdf,.doc,.docx', // 允许的文件类型
  maxSize: 10 * 1024 * 1024, // 10MB
  maxCount: 5, // 最多上传5个文件
  dragText: '点击或拖拽文件到此区域上传',
  hintText: '支持图片、PDF、Word文档，单个文件不超过10MB，也可以上传整个文件夹',
  buttonText: '选择文件',
  showButton: true,
  showPreview: true,
  showDownload: true,
  autoUpload: false, // 改为手动上传，便于演示
  allowFolder: true, // 启用文件夹上传
  folderMaxDepth: 1000, // 文件夹最大深度3层
  folderMaxFiles: 10000 // 文件夹内最多50个文件
};

// 上传前验证
const beforeUpload = (file: File) => {
  // 检查文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('不支持的文件类型！');
    return false;
  }
  
  // 检查文件大小
  if (file.size > uploadConfig.maxSize) {
    ElMessage.error('文件大小不能超过10MB！');
    return false;
  }
  
  return true;
};

// 上传成功回调
const onSuccess = (response: any, file: any) => {
  ElMessage.success(`${file.name} 上传成功！`);
  console.log('上传成功:', response, file);
};

// 上传失败回调
const onError = (error: any, file: any) => {
  ElMessage.error(`${file.name} 上传失败！`);
  console.error('上传失败:', error, file);
};

// 上传进度回调
const onProgress = (event: any, file: any) => {
  console.log('上传进度:', event, file);
};

// 文件删除回调
const onRemove = (file: any) => {
  ElMessage.info(`${file.name} 已删除`);
  console.log('文件删除:', file);
};

// 文件列表变化回调
const onChange = (files: any[]) => {
  fileList.value = files;
  console.log('文件列表变化:', files);
};

// 手动上传所有文件
const submitUpload = async () => {
  const readyFiles = fileList.value.filter(file => file.status === 'ready');
  
  if (readyFiles.length === 0) {
    ElMessage.warning('没有待上传的文件');
    return;
  }
  
  try {
    for (const file of readyFiles) {
      file.status = 'uploading';
      file.percentage = 0;
      
      try {
        const response = await uploadFile(file.raw, 'images', (progress) => {
          file.percentage = progress;
        });
        
        file.status = 'success';
        file.url = response.data?.url || response.data?.data?.url;
        file.response = response;
        
        ElMessage.success(`${file.name} 上传成功！`);
      } catch (error) {
        file.status = 'error';
        ElMessage.error(`${file.name} 上传失败！`);
        console.error('上传失败:', error);
      }
    }
  } catch (error) {
    ElMessage.error('上传过程中出现错误');
    console.error('上传错误:', error);
  }
};

// 清空文件列表
const clearFiles = () => {
  uploadRef.value?.clearFiles();
};

// 切换自动上传
const toggleAutoUpload = () => {
  uploadConfig.autoUpload = !uploadConfig.autoUpload;
  ElMessage.info(uploadConfig.autoUpload ? '已开启自动上传' : '已关闭自动上传');
};
</script>

<template>
	<div class="home-container">
		<div class="home-top-container">
			<h2>文件上传示例</h2>
		</div>
		
		<!-- 上传组件区域 -->
		<div class="upload-section">
			<Upload
				ref="uploadRef"
				v-model="fileList"
				v-bind="uploadConfig"
				:before-upload="beforeUpload"
				:on-success="onSuccess"
				:on-error="onError"
				:on-progress="onProgress"
				:on-remove="onRemove"
				@change="onChange"
			/>
			
			<!-- 操作按钮 -->
			<div class="upload-actions">
				<el-button type="primary" @click="submitUpload" :disabled="fileList.length === 0">
					手动上传
				</el-button>
				<el-button @click="clearFiles" :disabled="fileList.length === 0">
					清空列表
				</el-button>
				<el-button type="info" @click="toggleAutoUpload">
					{{ uploadConfig.autoUpload ? '关闭自动上传' : '开启自动上传' }}
				</el-button>
			</div>
			
			<!-- 文件统计信息 -->
			<div v-if="fileList.length > 0" class="file-stats">
				<el-tag type="info">总项目数: {{ fileList.length }}</el-tag>
				<el-tag type="primary">文件夹: {{ fileList.filter(f => f.isFolder).length }}</el-tag>
				<el-tag type="info">文件: {{ fileList.filter(f => !f.isFolder).length }}</el-tag>
				<el-tag type="success">成功: {{ fileList.filter(f => f.status === 'success').length }}</el-tag>
				<el-tag type="warning">上传中: {{ fileList.filter(f => f.status === 'uploading').length }}</el-tag>
				<el-tag type="danger">失败: {{ fileList.filter(f => f.status === 'error').length }}</el-tag>
			</div>
		</div>
		
		<div class="home-left-container"></div>
	</div>
</template>

<style scoped lang="scss">
.home-container {
	position: relative;
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	margin: 0;
	padding: 0;
}

.home-top-container {
	position: absolute;
	top: 0;
	left: 0;
	height: 100px;
	width: 100vw;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	
	h2 {
		color: white;
		margin: 0;
		font-size: 24px;
	}
}

.upload-section {
	position: absolute;
	top: 120px;
	left: 50%;
	transform: translateX(-50%);
	width: 80%;
	max-width: 800px;
	z-index: 1;
	background: white;
	border-radius: 8px;
	padding: 20px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.upload-actions {
	margin-top: 20px;
	display: flex;
	gap: 12px;
	justify-content: center;
}

.file-stats {
	margin-top: 15px;
	display: flex;
	gap: 8px;
	justify-content: center;
	flex-wrap: wrap;
}

.home-left-container {
	position: absolute;
	left: 0;
	top: 100px;
	z-index: 1;
	width: 150px;
	height: calc(100% - 100px);
	background-color: rgba(0, 0, 0, 0.5);
}

// 响应式设计
@media (max-width: 768px) {
	.upload-section {
		width: 95%;
		top: 110px;
		padding: 15px;
	}
	
	.home-top-container h2 {
		font-size: 20px;
	}
	
	.upload-actions {
		flex-direction: column;
		align-items: center;
		
		.el-button {
			width: 100%;
			max-width: 200px;
		}
	}
}
</style>
